<!-- 添加词库弹窗 -->
<style lang="scss" scoped>

.el-drawer__wrapper {
  ::v-deep {
    .el-drawer__header {
      margin-bottom: 10px;
    }
  }
}

.title {
  margin-bottom: 20px;
}

.search {

  margin-bottom: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  .el-input {
    width: 200px;
  }

  .el-button {
    margin-left: 10px;
  }
}

.scrollbar {
  height: calc(100vh - 240px)
}

.pagination-container {
  margin-top: 0;
}

</style>

<template>
  <el-drawer
    direction="ltr"
    :title="`${getTitle()} - ${showAddedList ? '已添加的关键词' : '添加关键词'}`"
    :visible.sync="showDialog"
    size="800px"
    custom-class="hjd-drawer"
    :wrapper-closable="true"
    @close="$emit('update:pVisible', false)"
  >
    <div class="drawer">
      <div class="hjd-drawer__content">

        <!-- 已添加的词库列表 -->
        <div v-show="showAddedList" class="words">

          <div class="search">
            <div>
              <el-input v-model="addedListQuery[type].keyword" size="mini" placeholder="请输入关键词" @keypress.enter.native="addedListQuery[type].page = 1, getAddedList()" />
              <el-button type="primary" size="mini" @click="addedListQuery[type].page = 1, getAddedList()">搜索</el-button>
            </div>

            <div>
              <el-button type="danger" size="mini" @click="deleteSelected">删除选中</el-button>
              <el-button v-show="showAddedList" type="primary" size="mini" @click="showAddedList = false, getList()">绑定关键词</el-button>
            </div>
          </div>

          <el-table
            ref="addedMultipleTable"
            v-loading="loading"
            :border="true"
            :data="addedTableData"
            height="calc(100vh - 200px)"
            style="width: 100%"
          >
            <el-table-column
              type="selection"
              align="center"
              width="50"
            />
            <el-table-column
              prop="word"
              label="关键词"
              width="width"
            />
          </el-table>

          <div>
            <pagination v-show="addedTotal > 0" :total="addedTotal" :page.sync="addedListQuery[type].page" :limit.sync="addedListQuery[type].limit" @pagination="getAddedList" />
          </div>
        </div>

        <div v-show="!showAddedList" class="search-words">
          <div class="search">
            <div>
              <el-input v-model="unBindListQuery[type].word" size="mini" placeholder="请输入关键词" @keypress.enter.native="doSearch" />
              <el-button type="primary" size="mini" icon="el-icon-search" @click="doSearch">搜索</el-button>
              <el-button type="success" size="mini" @click="addWord">加入词库</el-button>
            </div>

            <div>
              <el-button type="danger" size="mini" icon="el-icon-coordinate" @click="submit">绑定到词库</el-button>
              <el-button v-show="!showAddedList" type="primary" size="mini" @click="showAddedList = true, getAddedList()">查看已添加</el-button>
            </div>
          </div>

          <el-table
            ref="multipleTable"
            v-loading="loading"
            :border="true"
            :data="tableData"
            style="width: 100%"
            height="calc(100vh - 200px)"
            @select="handleSelectionChange"
            @select-all="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              align="center"
              width="50"
            />
            <el-table-column
              prop="word"
              label="关键词"
              width="width"
            />
          </el-table>

          <div>
            <pagination v-show="total > 0" :total="total" :page.sync="unBindListQuery[type].page" :limit.sync="unBindListQuery[type].limit" @pagination="getList" />
          </div>
        </div>

      </div>
    </div>
  </el-drawer>
</template>

<script>

import _ from 'lodash'

import {
  addWord as tariffAddWord,
  deleteWords as tariffDeleteWords,
  getBoundWords as tariffGetBoundWords,
  bindWord as tariffBindWord,
  unBind as tariffUnBind
} from '@/api/base/tariffWord'

import {
  addWord as brandAddWord,
  deleteWords as brandDeleteWords,
  getBoundWords as brandGetBoundWords,
  bindWord as brandBindWord,
  unBind as brandUnBind
} from '@/api/base/brand'

// hscodeWord
import { hscodeBindWord, hscodeBindDelete, hscodeAddWord, hscodeBindSearch, hscodeUnBind } from '@/api/base/hscode'

import Pagination from '@/components/Pagination'

export default {

  name: 'AddDictionary',

  components: {
    Pagination
  },

  props: {
    pVisible: {
      required: true,
      type: Boolean,
      default: false
    },

    /**
     * 完税价格表 | 品牌
     * @type { 'tariff' | 'brand' }
     */
    type: {
      required: true,
      type: String
    },

    pData: {
      required: true,
      type: Object,
      default: () => ({})
    }
  },

  data() {
    return {
      showDialog: this.pVisible,

      loading: false,

      unBindListQuery: {
        tariff: {
          word: '',
          tariff_id: this.pData.id,
          page: 1,
          limit: 20
        },

        brand: {
          word: '',
          brand_id: this.pData.brand_id,
          page: 1,
          limit: 20
        },

        hscode: {
          word: '',
          hscode_id: this.pData.hscode_id,
          page: 1,
          limit: 20
        }
      },

      /**
       * 已添加关键词请求参数
       */
      addedListQuery: {
        tariff: {
          keyword: '',
          tariff_id: this.pData.id,
          tax_code: this.pData.tax_code,
          page: 1,
          limit: 20
        },

        brand: {
          brand_id: this.pData.brand_id,
          brand_zh: this.pData.brand_name,
          brand_en: this.pData.brand_en_name,
          keyword: ''
        },

        hscode: {
          hscode_id: this.pData.hscode_id,
          keyword: '',
          page: 1,
          limit: 20
        }
      },

      showAddedList: true,

      /**
       * 显示添加关键词按钮
       */
      showAddWordButton: false,

      /**
       * 添加的关键词
       */
      addWords: [],

      total: 0,
      addedTotal: 0,

      tableData: [],
      addedTableData: [],
      /**
       * 批量删除
       */
      deleteAdded: []
    }
  },

  created() {
    // 获取已添加关键词列表
    this.getAddedList()
  },

  methods: {

    getTitle() {
      switch (this.type) {
        case 'tariff': return this.pData.name
        case 'brand': return this.pData.brand_name
        case 'hscode': return this.pData.name
      }
    },

    getAddedList() {
      this.loading = true

      let getBoundWords = null
      switch (this.type) {
        case 'tariff': getBoundWords = tariffGetBoundWords; break
        case 'brand': getBoundWords = brandGetBoundWords; break
        case 'hscode': getBoundWords = hscodeBindSearch; break
      }

      getBoundWords(this.addedListQuery[this.type]).then(res => {
        this.loading = false

        switch (this.type) {
          case 'tariff': this.addedTableData = res.data.data; break
          case 'brand': this.addedTableData = res.data.data; break
          case 'hscode': this.addedTableData = res.data; break
        }

        this.addedTotal = res.data.total || 0
      })
    },

    getList() {
      this.loading = true

      let unBind = null
      switch (this.type) {
        case 'tariff': unBind = tariffUnBind; break
        case 'brand': unBind = brandUnBind; break
        case 'hscode': unBind = hscodeUnBind; break
      }

      return unBind(this.unBindListQuery[this.type]).then(async res => {
        this.loading = false
        this.tableData = _.get(res, 'data.data', [])
        this.total = _.get(res, 'data.total', 0)

        // 如果没有绑定的关键词 则不用走下面的选中逻辑
        if (this.addWords.length === 0) return

        // 判断选中
        /*
        this.$nextTick(() => {
          // 选中
          _.forEach(this.tableData, (item, index) => {
            if (~this.addWords.indexOf(item.id)) {
              this.$refs.multipleTable.toggleRowSelection(this.tableData[index], true)
            }
          })
        })
        */
      })
    },

    async doSearch() {
      this.unBindListQuery[this.type].page = 1
      await this.getList()
      this.showAddWordButton = this.total === 0
    },

    handleSelectionChange(selection, row) {
      // 全选
      if (!row) {
        // 取消选择
        if (selection.length === 0) {
          _.forEach(this.tableData, item => {
            // 循环删除 ID
            // 如果存在 选中的关键词 中 则删除
            const addWordsIndex = this.addWords.indexOf(item.id)
            if (~addWordsIndex) {
              this.addWords.splice(addWordsIndex, 1)
            }
          })

        // 全选
        } else {
          _.forEach(this.tableData, item => {
            // 循环添加 ID
            // 如果 不存在 选取的关键词 中 则添加
            if (!~this.addWords.indexOf(item.id)) {
              this.addWords.push(item.id)
            }
          })
        }

        return
      }

      // 单选
      if (~selection.indexOf(row)) {
        // 如果 不存在 选取的关键词 中 则添加
        if (!~this.addWords.indexOf(row.id)) {
          this.addWords.push(row.id)
        }

      // 取消选中
      } else {
        // 如果存在 选中的关键词 中 则删除
        const addWordsIndex = this.addWords.indexOf(row.id)
        if (~addWordsIndex) {
          this.addWords.splice(addWordsIndex, 1)
        }
      }
    },

    /**
     * 删除选中关键词
     */
    deleteSelected() {
      const selected = this.$refs.addedMultipleTable.selection
      if (selected.length === 0) {
        this.$message.error('请选择需要删除的关键词')
        return
      }

      this.$confirm('确认删除?').then(() => {
        // 请求完接口后删除表格数组中对应的关键词
        this.loading = true

        const ids = selected.map(item => item.word_id).join(',')

        let deleteWords = null
        let params = null
        switch (this.type) {
          case 'tariff': {
            deleteWords = tariffDeleteWords
            params = {
              tariff_id: this.pData.id,
              word_id: ids
            }
            break
          }
          case 'brand': {
            deleteWords = brandDeleteWords
            params = {
              brand_id: this.pData.brand_id,
              word_id: ids
            }
            break
          }

          case 'hscode': {
            deleteWords = hscodeBindDelete
            params = {
              hscode_id: this.pData.hscode_id,
              word_id: ids
            }
            break
          }
        }

        deleteWords(params).then(() => {
          this.loading = false
          this.$message.success('删除成功')
          // 刷新列表
          this.getAddedList()
        })
      }).catch(() => {})
    },

    /**
     * 添加词库没有的关键词
     */
    addWord() {
      let addWord = null
      let params = null
      const word = _.get(this.unBindListQuery[this.type], 'word', '')
      switch (this.type) {
        case 'tariff': {
          addWord = tariffAddWord
          params = {
            tariff_id: this.pData.id,
            word
          }
          break
        }

        case 'brand': {
          addWord = brandAddWord
          params = {
            brand_id: this.pData.brand_id,
            word
          }
          break
        }

        case 'hscode': {
          addWord = hscodeAddWord
          params = {
            hscode_id: this.pData.hscode_id,
            word
          }
        }
      }

      // 提交后台
      addWord(params).then(res => {
        this.$message.success('添加成功')
        this.showAddWordButton = false
        this.getList()
      })
    },

    /**
     * 绑定关键词
     */
    submit() {
      let bindWord = null
      let params = null
      const ids = this.addWords.join(',')
      switch (this.type) {
        case 'tariff': {
          bindWord = tariffBindWord
          params = {
            tariff_id: this.pData.id,
            word_id: ids
          }
          break
        }

        case 'brand': {
          bindWord = brandBindWord
          params = {
            brand_id: this.pData.brand_id,
            word_id: ids
          }
          break
        }

        case 'hscode': {
          bindWord = hscodeBindWord
          params = {
            hscode_id: this.pData.hscode_id,
            word_id: ids
          }
        }
      }

      bindWord(params).then(() => {
        this.$message.success('添加成功')
        this.getList()
        this.showAddWordButton = false
      })
    }
  }
}
</script>
